package com.justech.mes.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;

/**
 * @author feifei.li
 */
public class QrcodeUtil {

    public static void main(String[] args) {
        int width = 300;
        int height = 300;
        String format = "jpg";
        String contents = "JSB19001-E-3496-10";
        int initialCapacity = 3;
        HashMap map = new HashMap(initialCapacity);
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 0);
        try {
            BitMatrix bm = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height);

            Path file = new File("D:/img.jpg").toPath();
            MatrixToImageWriter.writeToPath(bm, format, file);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void read() {
        try {
            /*Partners who need to know more about MultiFormatReader can point me to the official document.*/
            Reader reader = new MultiFormatReader();
            File f = new File("D:/img.png");
            BufferedImage image = ImageIO.read(f);
            BinaryBitmap bb = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            int initialCapacity = 3;
            HashMap map = new HashMap(initialCapacity);
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");
            Result result = reader.decode(bb, map);
            System.out.println("解析结果：" + result.toString());
            System.out.println("二维码格式类型：" + result.getBarcodeFormat());
            System.out.println("二维码文本内容：" + result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
